package com.sky.service.impl;

import ch.qos.logback.core.joran.util.beans.BeanUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.dto.PasswordEditDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordEditFailedException;
import com.sky.exception.PasswordErrorException;
import com.sky.interceptor.JwtTokenAdminInterceptor;
import com.sky.mapper.EmployeeMapper;
import com.sky.properties.JwtProperties;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import com.sky.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.security.MD5Encoder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

@Slf4j
@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Resource
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // 后期需要进行md5加密，然后再进行比对
        //对前端传入的密码进行加密
        String pwdMD5 = DigestUtils.md5DigestAsHex(password.getBytes());
        //System.out.println(pwdMD5);
        String dbPwd = employee.getPassword();
        if (!pwdMD5.equals(dbPwd)) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus().equals(StatusConstant.DISABLE)) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    /**
     * 添加员工
     *
     * @param employeeDTO
     */
    @Override
    public void insertEmployee(EmployeeDTO employeeDTO) {
        Employee employee = Employee.builder()
                .password(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()))
                .status(StatusConstant.ENABLE)
                .build();
        BeanUtils.copyProperties(employeeDTO, employee);
        employeeMapper.insertEmployee(employee);
    }

    /**
     * 分页查询员工信息
     *
     * @param employeePageQueryDTO
     * @return
     */
    @Override
    public PageResult selectEmp(EmployeePageQueryDTO employeePageQueryDTO) {
        //使用PageHelper将分页的每页条数和页数当参数传进去
        PageHelper.startPage(employeePageQueryDTO.getPage(), employeePageQueryDTO.getPageSize());
        //将查询到的数据存入Page集合中
        Page<Employee> pageResult = employeeMapper.selectEmp(employeePageQueryDTO);
        log.info("员工一共有{}人", pageResult.getTotal());
        return PageResult.builder().total(pageResult.getTotal()).records(pageResult.getResult()).build();
    }

    /**
     * 启用禁用员工
     *
     * @param status
     * @param id
     */
    @Override
    public void updateStatus(Integer status, Long id) {
        Employee employee = Employee.builder().status(status).id(id).build();
        //更新时间
        //employee.setUpdateTime(LocalDateTime.now());
        //更新ID
        //employee.setUpdateUser(BaseContext.getCurrentId());
        employeeMapper.updateEmployee(employee);
    }

    /**
     * 根据ID查员工信息
     *
     * @param id
     * @return
     */
    @Override
    public Employee selectEmpById(Long id) {
        Employee employee = employeeMapper.selectEmpById(id);
        return employee;
    }

    /**
     * 修改员工信息
     *
     * @param employee
     */
    @Override
    public void updateEmployee(Employee employee) {
        //更新时间
        //employee.setUpdateTime(LocalDateTime.now());
        //更新ID
        //employee.setUpdateUser(BaseContext.getCurrentId());
        //更新信息
        employeeMapper.updateEmployee(employee);
    }

    /**
     * 修改密码
     *
     * @param passwordEditDTO
     */
    @Override
    public void updatePassword(PasswordEditDTO passwordEditDTO) {
        passwordEditDTO.setEmpId(BaseContext.getCurrentId());//传入操作账号的ID
        String newPassword = DigestUtils.md5DigestAsHex(passwordEditDTO.getNewPassword().getBytes());//新密码加密
        String oldPassword = DigestUtils.md5DigestAsHex(passwordEditDTO.getOldPassword().getBytes());//旧密码加密
        //拿到数据库中的密码
        String getPassword = employeeMapper.selectEmpPasswordById(passwordEditDTO.getEmpId());
        if(!getPassword.equals(oldPassword)){
            throw new PasswordEditFailedException("输入的旧密码错误");
        }
        //log.info("牛逼");
        if (!newPassword.equals(oldPassword)) {
            Employee employee = Employee.builder()
                    .id(passwordEditDTO.getEmpId()) //传入ID
                    .password(newPassword)          //新密码
                    .build();
            log.info("密码为 : {}",newPassword);
            employeeMapper.updateEmployee(employee);
        }else{
            throw new PasswordEditFailedException("新密码不能与旧密码相同!");
        }
    }
}
